<?php
/**
 * Permissions management model
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Usermanagement Module
 * @subpackage Model
 * @license  New BSD License
 *
 */
class Models_Usermanagement_Permissions extends Bel_Model_Abstract {	
	/**
	 * Array of many-to-one references with groups & modules table
	 *
	 * @var array
	 */	
	protected $_referenceMap = array (
									 'Group' => 
											array ('columns' => 'user_group_id',
												   'refTableClass' => 'Models_Usermanagement_Groups',
									   			   'refColumns' => 'user_group_id', 
												   'onDelete' => self::CASCADE
									   			   ),
									 'Modules' => 
											array ('columns' => 'module_id',
												   'refTableClass' => 'Models_Modules',
									   			   'refColumns' => 'module_id',
												   'onDelete' => self::CASCADE 
									   			   ),
									  );	
	
	
	/**
	 * Constructor. Sets table name & primary key
	 *
	 * @param array $array - see Zend_Db_Table_Abstract for details
	 */
	public function __construct($array = array()) {
		$this->_name = TABLE_PREFIX . 'permissions';
		$this->_primary = array ('permission_id' );
		parent::__construct ( $array );
	
	}	
	/**
	 * Adds permissions
	 *
	 * @param int $group_id
	 * @param array $newactions - array modules to aloow access to
	 * @param int $controller_or_module_id
	 */
	public function addPermissions($group_id, $newactions, $controller_or_module_id) {
		$modules = new Models_Usermanagement_Modules();
		$actions = $modules->getTreeBranch ( $controller_or_module_id, 'module_level = 4' );
		
		foreach ( $actions as $action ) {
			$this->delPermissionByGroupAndAction ( $group_id, $action->module_id );
		}
		
		foreach ( $newactions as $key => $action ) {
			$row = $this->createRow ();
			$row->user_group_id = $group_id;
			$row->module_id = $key;
			$row->save();
		}
	}	
	/**
	 * Deletes permissions for group to action
	 *
	 * @param int $group_id
	 * @param int $action_id
	 */
	private function delPermissionByGroupAndAction($group_id, $action_id) {
		$where = array ('user_group_id=' . $group_id, 'module_id=' . $action_id );
		$this->delete ( $where );
	}	
	/**
	 * Returns permission for group to action
	 *
	 * @param int $group_id
	 * @param int $action_id
	 * @return int
	 */
	public function getPermissionByGroupAndAction($group_id, $action_id) {
		$where = array ('user_group_id = ?' => $group_id, 'module_id = ?' => $action_id );
		return ($row = $this->fetchRow ( $where )) ? $row->module_id : NULL;
	}
}